﻿namespace Digitalmes.Application.Mes;

/// <summary>
/// 枚举列表
/// </summary>
[AllowAnonymous]
[ApiExplorerSettings(GroupName = "mes")]
public sealed class EnumListService : IDynamicWebApiService
{
    /// <summary>
    /// 通过枚举类型获取枚举值集合
    /// </summary>
    /// <param name="name">枚举类型名称</param>
    /// <returns></returns>
    [HttpGet("{name}")]
    public List<EnumDto> Get(string name)
    {
        // 找到属于 ErrCode 类型的程序集下指定的枚举类型
        Type type = typeof(ErrCode).Assembly.GetTypes().FirstOrDefault(t => t.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) ?? throw Oops.Bah(ErrCode.E4004);

        var arr = Enum.GetNames(type);
        return arr.Select(sl =>
        {
            var item = Enum.Parse(type, sl);
            return new EnumDto
            {
                Label = GetDescription(item) ?? item.ToString(),
                Value = item.GetHashCode()
            };
        }).ToList();
    }

    private static string? GetDescription(object value)
    {
        return value.GetType().GetMember(value.ToString() ?? string.Empty)
            .FirstOrDefault()?.GetCustomAttribute<DescriptionAttribute>()?.Description;
    }
}
